#region File Description
//-----------------------------------------------------------------------------
// MenuScreen.cs
//
// XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion

namespace TankWars
{
    /// <summary>
    /// Base class for screens that contain a menu of options. The user can
    /// move up and down to select an entry, or cancel to back out of the screen.
    /// </summary>
    abstract class MenuScreen : GameScreen
    {
        #region Fields

        List<MenuEntry> menuEntries = new List<MenuEntry>();
        int selectedEntry = 0;
        string menuTitle;

        // Used by both options menu and pause menu to toggle full-screen
        static bool fullScreenOn = false;

        #endregion

        #region Properties


        /// <summary>
        /// Gets the list of menu entries, so derived classes can add
        /// or change the menu contents.
        /// </summary>
        protected IList<MenuEntry> MenuEntries
        {
            get { return menuEntries; }
        }

        // Access for toggling full-screen
        protected static bool FullScreenOn
        {
            get { return MenuScreen.fullScreenOn; }
            set { MenuScreen.fullScreenOn = value; }
        }


        #endregion

        #region Initialization


        /// <summary>
        /// Constructor.
        /// </summary>
        public MenuScreen(string menuTitle)
        {
            // Every menu has to have a title
            this.menuTitle = menuTitle;

            // Set time for transition between menus
            TransitionOnTime = TimeSpan.FromSeconds(0.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
        }


        #endregion

        #region Handle Input


        /// <summary>
        /// Responds to user input, changing the selected entry and accepting
        /// or cancelling the menu.
        /// </summary>
        public override void HandleInput(InputState input)
        {
            // Move to the previous menu entry?
            if (input.MenuUp)
            {
                selectedEntry--;

                if (selectedEntry < 0)
                {
                    selectedEntry = menuEntries.Count - 1;
                }
            }

            // Move to the next menu entry?
            if (input.MenuDown)
            {
                selectedEntry++;

                if (selectedEntry >= menuEntries.Count)
                {
                    selectedEntry = 0;
                }
            }

            // Accept or cancel the menu?
            if (input.MenuSelect)
            {
                OnSelectEntry(selectedEntry);
            }
            else if (input.MenuCancel)
            {
                OnCancel();
            }

            
            // Create mouse "rectangle" for collision
            Rectangle mouseRect = new Rectangle((int)input.CurrentMouseCoords.X, (int)input.CurrentMouseCoords.Y, 0, 0);
            // Compare each menu entry in turn                
            for (int i = 0; i < menuEntries.Count; i++)
            {
                // Make a rectangle for the entry
                Rectangle entryRect = new Rectangle((int)(menuEntries[i].MenuPosition.X - (ScreenManager.Font.MeasureString(menuEntries[i].Text).X / 2)), (int)(menuEntries[i].MenuPosition.Y - (ScreenManager.Font.MeasureString(menuEntries[i].Text).Y / 2)), (int)menuEntries[i].GetDimensions(this).X, (int)menuEntries[i].GetDimensions(this).Y);
                // If the mouse is on the entry, change selection
                if (mouseRect.Intersects(entryRect))
                {
                    // Determine if the mouse has moved at least 2 pixels
                    if (Math.Abs(input.CurrentMouseCoords.X - input.LastMouseCoords.X) > 2 ||
                        (input.CurrentMouseCoords.Y - input.LastMouseCoords.Y) > 2)
                    {
                        // Then highlight
                        selectedEntry = i;
                    }

                    // A click is noted?
                    if (input.MenuClick)
                    {
                        // Go to selected screen
                        OnSelectEntry(selectedEntry);
                    }
                }

            }
        }


        /// <summary>
        /// Handler for when the user has chosen a menu entry.
        /// </summary>
        protected virtual void OnSelectEntry(int entryIndex)
        {
            menuEntries[selectedEntry].OnSelectEntry();
        }


        /// <summary>
        /// Handler for when the user has cancelled the menu.
        /// </summary>
        protected virtual void OnCancel()
        {
            ExitScreen();
        }


        /// <summary>
        /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
        /// </summary>
        protected void OnCancel(object sender, EventArgs e)
        {
            OnCancel();
        }



        #endregion

        #region Update and Draw


        /// <summary>
        /// Updates the menu.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            // Make the menu slide into place during transitions, using a
            // power curve to make things look more interesting (this makes
            // the movement slow down as it nears the end).
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
            Vector2 tempPosition;
            
            // Update each nested MenuEntry object.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                bool isSelected = IsActive && (i == selectedEntry);
                                
                tempPosition = menuEntries[i].MenuPosition;

                // New X transition position
                if (ScreenState == ScreenState.TransitionOn)
                    menuEntries[i].UpdateEntryX((ScreenManager.GraphicsDevice.Viewport.Width / 2) - transitionOffset * 256);
                else
                    menuEntries[i].UpdateEntryX((ScreenManager.GraphicsDevice.Viewport.Width / 2));
                // New Y transition position
                menuEntries[i].UpdateEntryY((float)((ScreenManager.GraphicsDevice.Viewport.Height * 0.3) + (i * 1.75 * menuEntries[i].GetHeight(this))));

                menuEntries[i].Update(this, isSelected, gameTime);
            }
        }


        /// <summary>
        /// Draws the menu.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            SpriteFont menuFont = ScreenManager.Font;

            spriteBatch.Begin();

            // Update X position and draw each menu entry in turn.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                bool isSelected = IsActive && (i == selectedEntry);

                menuEntries[i].Draw(this, isSelected, gameTime);                
            }

            // Draw the menu title.
            Vector2 titlePosition = new Vector2((ScreenManager.GraphicsDevice.Viewport.Width / 2), 80);
            Vector2 titleOrigin = menuFont.MeasureString(menuTitle) / 2;
            Color titleColor1 = new Color(255, 255, 255, TransitionAlpha);
            Color titleColor2 = new Color(0, 0, 0, TransitionAlpha);
            float titleScale = 1.75f;

            //titlePosition.Y -= transitionOffset * 100;

            // Draw title in pseudo-3D form            
            spriteBatch.DrawString(menuFont, menuTitle, titlePosition + new Vector2(3), titleColor2, 0,
                                   titleOrigin, titleScale, SpriteEffects.None, 0);
            spriteBatch.DrawString(menuFont, menuTitle, titlePosition, titleColor1, 0,
                                   titleOrigin, titleScale, SpriteEffects.None, 0);

            spriteBatch.End();
        }


        #endregion
    }
}
